﻿using Volo.Abp.Domain.Services;
using YAPACS.BusinessObjects.Exams;
using YAPACS.Organizations;
using YAPACS.RisServer.Abstractions;

namespace YAPACS.RisServer.Services;

public class ExamPermissionService : DomainService, IExamPermissionService
{
    private readonly ICurrentUserOrganization _currentUserOrganization;

    public ExamPermissionService(ICurrentUserOrganization currentUserOrganization)
    {
        _currentUserOrganization = currentUserOrganization;
    }

    private Task InternalValidateAsync(Exam exam, bool isValidateExpertGroup)
    {
        if (exam.Department?.Id != _currentUserOrganization.DepartmentId)
        {
            if (isValidateExpertGroup && exam.ExpertGroup != null)
            {
                if (exam.ExpertGroup.Users.Any(u => u.Id == _currentUserOrganization.UserId))
                {
                    return Task.CompletedTask;
                }
            }
            throw new Exception("无法操作不属于本科室的检查");
        }
        return Task.CompletedTask;
    }

    private Task InternalValidateAsync(Exam exam, ApplicationUser user)
    {
        if (!user.UserGroups.Select(g => g.Department).Contains(exam.Department))
        {
            if (exam.ExpertGroup != null)
            {
                if (exam.ExpertGroup.Users.Any(u => u.Id == user.Id))
                {
                    return Task.CompletedTask;
                }
            }
            throw new Exception("无法操作不属于本科室的检查");
        }
        return Task.CompletedTask;
    }

    public async Task<bool> IsValidAsync(Exam exam, bool isValidateExpertGroup = false)
    {
        try
        {
            await InternalValidateAsync(exam, isValidateExpertGroup);
            return true;
        }
        catch
        {
            return false;
        }
    }

    public async Task ValidateAsync(Exam exam, bool isValidateExpertGroup = false)
    {
        await InternalValidateAsync(exam, isValidateExpertGroup);
    }

    public async Task<bool> IsValidAsync(Exam exam, ApplicationUser user)
    {
        try
        {
            await InternalValidateAsync(exam, user);
            return true;
        }
        catch
        {
            return false;
        }
    }

    public async Task ValidateAsync(Exam exam, ApplicationUser user)
    {
        await InternalValidateAsync(exam, user);
    }
}
